import React, { useCallback, useRef } from 'react'
import { Card } from 'antd'
import View from '@/components/View'
import { observer } from 'mobx-react'
import { useSortTable } from '@/hooks/table/useSortTable'
import { useTableLazyLoad } from '@/hooks/table/useLazyLoadTable'
import { useStore } from '@/store'
import { toJS } from 'mobx'

interface ContainerProps {
  children: React.ReactNode;
  onScroll: (e: React.UIEvent<HTMLDivElement>) => void;
  containerRef: React.RefObject<HTMLDivElement>;
}

// 容器组件
const ScrollContainer: React.FC<ContainerProps> = ({ children, onScroll, containerRef }) => {
  return (
    <div
      ref={containerRef}
      style={{ height: '400px', overflow: 'auto' }}
      onScroll={onScroll}
    >
      {children}
    </div>
  )
}

// 表格组件
const DataTable: React.FC<{ data: any[], onSort: (key: string) => void }> = ({ data, onSort }) => {
  return (
    <div className="ant-table-wrapper">
      <div className="ant-table-content">
        <table className="ant-table">
          <thead className="ant-table-thead">
            <tr>
              <th onClick={() => onSort('id')}>
                ID
              </th>
              <th>name</th>
              <th>phone</th>
            </tr>
          </thead>
          <tbody className="ant-table-tbody">
            {data?.map((item, index) => (
              <tr key={`${item.phone}_${index}`}>
                <td>{item.id.name}</td>
                <td>{item.name.title}</td>
                <td>{item.phone}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

const LazyTable = () => {
  const containerRef1 = useRef<HTMLDivElement>(null)
  // const containerRef2 = useRef<HTMLDivElement>(null)
  // const containerRef3 = useRef<HTMLDivElement>(null)
  const { tableStore } = useStore()
  const { sortedData, requestSort } = useSortTable(toJS(tableStore?.list))
  const { loading, loadMore } = useTableLazyLoad()

  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget
    if (scrollHeight - scrollTop - clientHeight < 50) {
      loadMore()
    }
  }, [loadMore])

  return (
    <View className="app-lazy-table">
      <Card title="懒加载表格">
        <ScrollContainer containerRef={containerRef1} onScroll={handleScroll}>
          <DataTable
            data={sortedData}
            onSort={requestSort}
          />
        </ScrollContainer>
        <div className="flex justify-center pt-5">
          {loading && <div>...loading</div>}
        </div>
      </Card>
    </View>
  )
}

export default observer(LazyTable)
